package com.dxb.test.caffeine;

import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author DLS
 */
public class DataSourceAsyncLoadingCache {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        AsyncLoadingCache<String, DataSource> cache = Caffeine.newBuilder()
                .maximumSize(10_000)
                .expireAfterWrite(10, TimeUnit.SECONDS)
                // 你可以选择: 去异步的封装一段同步操作来生成缓存元素
                .buildAsync(key -> createExpensiveGraph(key));

        // 查找缓存元素，如果其不存在，将会异步进行生成
        CompletableFuture<DataSource> graph = cache.get("ds5ls");
        System.out.println("第一次取:" + graph.get().getName());
        graph = cache.get("ds5ls");
        System.out.println("第二次取:" + graph.get().getName());
        Thread.sleep(11000);
        graph = cache.get("ds5ls");
        System.out.println("第三次取(过期):" + graph.get().getName());
    }

    private static DataSource createExpensiveGraph(String key) throws InterruptedException {
        System.out.println("creating");
        Thread.sleep(5000L);
        System.out.println("created");
        return new DataSource(key, 1);
    }

}
